<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template #status="{row}">
        <el-tag v-if="row.status === 1" size="small" type='warning'>区县管理员审核中</el-tag>
        <el-tag v-if="row.status === 2" size="small" type="success">区县管理员审批通过</el-tag>
        <el-tag v-if="row.status === 3" size="small" type="danger">区县管理员审批不通过</el-tag>
      </template>
      <template slot-scope="scope" slot="menuForm">
        <el-button type="primary" size="small" icon="el-icon-document-checked"  @click="handleDownload(form)">下载审批附件</el-button>
        <el-button v-if="userInfo.role_name.includes('districtAdmin')" type="info" size="small" icon="el-icon-close" @click.stop="handleEdits(form)">审批不通过</el-button>
        <el-button v-if="userInfo.role_name.includes('districtAdmin')" type="success" size="small" icon="el-icon-check" @click.stop="handleEdit(form)">审批通过</el-button>
      </template>
      <template slot="menuLeft">
        <el-button type="primary"
                   size="small"
                   plain
                   v-if="userInfo.role_name.includes('medical')"
                   icon="el-icon-upload2"
                   @click="handleUpload">申请线下采购
        </el-button>
      </template>
      <template slot="menuLeft">
        <el-button type="primary"
                   size="small"
                   plain
                   v-if="userInfo.role_name.includes('medical')"
                   icon="el-icon-upload2"
                   @click="handleTemplate">下载模板
        </el-button>
      </template>
      <template slot-scope="{row}"
                slot="attachSize">
        <el-tag>{{`${row.attachSize} KB`}}</el-tag>
      </template>
    </avue-crud>
    <el-dialog title="申请线下采购"
               append-to-body
               :visible.sync="attachBox"
               width="555px">
      <avue-form ref="form" :option="attachOption" v-model="attachForm" :upload-after="uploadAfter">
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, getDetail,template, add, update, remove, examine } from "@/api/business/offlinePurchase";
import option from "@/const/business/offlinePurchase";
  import {mapGetters} from "vuex";
import {exportBlob} from "@/api/common";
import {getToken} from "@/util/auth";
import {downloadXls} from "@/util/util";

  export default {
    data() {
      return {
        attachForm: {},
        attachBox: false,
        attachOption: {
          submitBtn: false,
          emptyBtn: false,
          column: [
            {
              label: '附件上传',
              prop: 'attachFile',
              type: 'upload',
              drag: true,
              loadText: '附件上传中，请稍等',
              span: 24,
              propsHttp: {
                res: 'data'
              },
              action: "/api/blade-offlinePurchase/offlinePurchase/import-file"
            }
          ]
        },
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: option,
        data: []
      };
    },
    created(){
      let district = this.findObject(this.option.column,'district');
      let instName = this.findObject(this.option.column,'instName');
      if(this.userInfo.role_name==="medical"){
        district.searchDisabled=true
        instName.searchDisabled=true
        district.searchValue=this.loginUserInfo.institution.district
        instName.searchValue=this.loginUserInfo.institution.instName
        this.$set(this.query,"instName",instName.searchValue)
        this.$set(this.query,"district",district.searchValue)
      }
      if(this.userInfo.role_name==="districtAdmin"){
        district.searchDisabled=true
        district.searchValue=this.loginUserInfo.dept.remark
        this.$set(this.query,"district",district.searchValue)
      }
    },
    computed: {
      ...mapGetters(["userInfo","permission","loginUserInfo"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.offlinePurchase_add, false),
          viewBtn: this.vaildData(this.permission.offlinePurchase_view, true),
          delBtn: this.vaildData(this.permission.offlinePurchase_delete, false),
          editBtn: this.vaildData(this.permission.offlinePurchase_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      handleUpload() {
        this.attachBox = true;
      },
      uploadAfter(res, done, loading, column) {
        window.console.log(column);
        this.attachBox = false;
        this.refreshChange();
        done();
      },
      handleTemplate() {
        template().then(res => {
          window.open(res.data.data);
        });
      },
      handleDownload(form) {
        window.open(`${form.filepath}`);
      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      handleEdit(form) {
        console.log(this.userInfo.role_name,this.userInfo.role_name)
        this.$confirm("确认审批通过此数据?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            form.status = 2
            return examine(form);
            loading: false
          })
          .then(() => {
            this.onLoad(this.page);
            this.$refs.crud.$refs.dialogForm.closeDialog()
            this.$message({
              type: "success",
              message: "操作成功!"

            });
          });
      },
      handleEdits(form) {
        console.log(form,"6666")
        this.$confirm("确认驳回此数据?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            form.status = 3
            return examine(form);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$refs.crud.$refs.dialogForm.closeDialog()
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
